from django.db import models
import uuid
import os
from django.conf import settings

class KnowledgeBase(models.Model):
    """知识库主表"""
    TYPE_CHOICES = [
        ('标准', '标准'),
        ('知识', '知识'),
    ]
    
    STATUS_CHOICES = [
        ('在用', '在用'),
        ('已发布', '已发布'),
        ('废止', '废止'),
    ]
    
    CATEGORY_CHOICES = [
        ('安全管理', '安全管理'),
        ('设备维护', '设备维护'),
        ('应急预案', '应急预案'),
        ('操作规程', '操作规程'),
        ('技术标准', '技术标准'),
    ]

    knowledge_id = models.CharField('知识编号', max_length=50, primary_key=True, unique=True)
    title = models.CharField('标题', max_length=200)
    content_type = models.CharField('内容类型', max_length=10, choices=TYPE_CHOICES)
    category = models.CharField('分类', max_length=20, choices=CATEGORY_CHOICES)
    status = models.CharField('状态', max_length=10, choices=STATUS_CHOICES, default='已发布')
    view_count = models.IntegerField('浏览次数', default=0)
    uploader = models.CharField('上传人', max_length=50)
    upload_date = models.DateTimeField('上传日期', auto_now_add=True)
    keywords = models.CharField('关键字', max_length=500, blank=True, help_text='多个关键词用逗号分隔')
    summary = models.TextField('内容摘要', max_length=500)
    # 改为存储文件路径字符串，不使用FileField
    file_path = models.CharField('附件路径', max_length=500, blank=True, help_text='相对于knowledge_files目录的文件路径')
    file_name = models.CharField('文件名', max_length=255, blank=True)
    file_size = models.BigIntegerField('文件大小', default=0, help_text='文件大小（字节）')
    
    class Meta:
        verbose_name = '知识库'
        verbose_name_plural = '知识库'
        db_table = 'knowledge_base'
        ordering = ['-upload_date']

    def save(self, *args, **kwargs):
        # 自动生成知识编号
        if not self.knowledge_id:
            from datetime import datetime
            count = KnowledgeBase.objects.count()
            self.knowledge_id = f"KB{datetime.now().strftime('%Y%m%d')}-{count + 1:03d}"
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.knowledge_id} - {self.title}"

    def get_absolute_file_path(self):
        """获取文件的绝对路径"""
        if self.file_path:
            knowledge_dir = os.path.join(settings.BASE_DIR, 'knowledge_files')
            return os.path.join(knowledge_dir, self.file_path)
        return ""

    def get_file_size_display(self):
        """获取格式化的文件大小"""
        if self.file_size == 0:
            return "0 B"
        
        size = self.file_size
        if size < 1024:
            return f"{size} B"
        elif size < 1024 * 1024:
            return f"{size / 1024:.1f} KB"
        else:
            return f"{size / (1024 * 1024):.1f} MB"

    def get_file_extension(self):
        """获取文件扩展名"""
        if self.file_name:
            return os.path.splitext(self.file_name)[1].lower()
        return ""

    def file_exists(self):
        """检查文件是否存在"""
        absolute_path = self.get_absolute_file_path()
        return os.path.exists(absolute_path) if absolute_path else False

class KnowledgeDetail(models.Model):
    """知识详情表"""
    content_id = models.UUIDField('内容ID', primary_key=True, default=uuid.uuid4, editable=False)
    knowledge = models.OneToOneField(KnowledgeBase, on_delete=models.CASCADE, related_name='detail')
    title = models.CharField('标题', max_length=200)
    summary = models.TextField('摘要', max_length=1000)
    content = models.TextField('详细内容', blank=True)
    attachment_path = models.CharField('附件路径', max_length=500, blank=True)
    uploader = models.CharField('上传人', max_length=50)
    upload_time = models.DateTimeField('上传时间', auto_now_add=True)
    view_count = models.IntegerField('浏览次数', default=0)

    class Meta:
        verbose_name = '知识详情'
        verbose_name_plural = '知识详情'
        db_table = 'knowledge_detail'

    def __str__(self):
        return self.title
